package controllers

import (
	beego "github.com/beego/beego/v2/server/web"
	"user/models"
)

type UserController struct {
	beego.Controller
}

func (c *UserController) Del() {
	ID, _ := c.GetInt("id")
	err := models.DB.Where("ID=?", ID).Delete(&models.Staff{}).Error
	if err != nil {
		c.Data["json"] = map[string]interface{}{
			"code": 500,
			"msg":  "删除失败",
		}
		c.ServeJSON()
		return
	}
	c.Data["json"] = map[string]interface{}{
		"code": 200,
		"msg":  "删除成功",
	}
	c.ServeJSON()
	return
}

func (c *UserController) Login() {
	username := c.GetString("username")
	password := c.GetString("password")

	if username == "" || password == "" {
		c.Data["json"] = map[string]interface{}{
			"code": 500,
			"msg":  "参数错误",
		}
		c.ServeJSON()
		return
	}

}

func (c *UserController) Add() {
	name := c.GetString("name")
	price, _ := c.GetInt("price")
	num, _ := c.GetInt("num")
	staff := models.Staff{
		Name:  name,
		Price: price,
		Num:   num,
	}
	err := models.DB.Create(&staff).Error
	if err != nil {
		c.Data["json"] = map[string]interface{}{
			"code": 500,
			"msg":  "添加失败",
		}
		c.ServeJSON()
		return
	}
	c.Data["json"] = map[string]interface{}{
		"code": 200,
		"msg":  "添加成功",
	}
	c.ServeJSON()
	return
}

func (c *UserController) List() {
	var Staffs []models.Staff
	name := c.GetString("name")
	err := models.DB.Where("name like ?", "%"+name+"%").Find(&Staffs).Error
	if err != nil {
		c.Data["json"] = map[string]interface{}{
			"code": 500,
			"msg":  "查询失败",
		}
		c.ServeJSON()
		return
	}
	c.Data["json"] = map[string]interface{}{
		"code": 200,
		"msg":  "查询成功",
	}
	c.ServeJSON()
	return
}

func (c *UserController) upload() {
	ID, _ := c.GetInt("id")
	name := c.GetString("name")
	price, _ := c.GetInt("price")
	num, _ := c.GetInt("num")
	staff := models.Staff{
		Name:  name,
		Price: price,
		Num:   num,
	}
	err := models.DB.Where("ID=?", ID).Create(&staff).Error
	if err != nil {
		c.Data["json"] = map[string]interface{}{
			"code": 500,
			"msg":  "修改失败",
		}
		c.ServeJSON()
		return
	}
	c.Data["json"] = map[string]interface{}{
		"code": 200,
		"msg":  "修改成功",
	}
	c.ServeJSON()
	return
}
